// 科室评价
import { FC, useEffect, useState, useRef, Key, ReactElement } from 'react'
import {
  connect,
  Loading,
  EvaluationStateType,
  Dispatch,
  PointInfoType,
  schoolInfoType,
  history
} from 'umi'
import {
  Tree,
  Breadcrumb,
  Table,
  Radio,
  Button,
  message,
  Form,
  Input,
  Select
} from 'antd'
const { Option } = Select
import { treeFindPath, getParentKeys, getChildKeys, setStorage } from '@/utils'
import type { DataNode, TreeProps } from 'antd/es/tree'
import type { FormInstance } from 'antd'
import { Location } from 'history-with-query'
import styles from './index.less'

interface IProps {
  dispatch: Dispatch
  evaluationModel: EvaluationStateType
  location: Location
}

interface FormValues {
  [name: string]: any
}
const OfficeEvaluationPage: FC<IProps> = ({
  dispatch,
  evaluationModel,
  location
}): ReactElement => {
  const { batchCode, type, questionCode, page } = location.query as {
    batchCode: string
    type: string
    questionCode: string
    page: string
  }
  const { pointInfo, pointDetail, scoreRules, schoolInfo, gradeList } =
    evaluationModel
  const formRef = useRef<FormInstance>(null)
  const [breadcrumb, setBreadcrumb] = useState<string[]>([])
  const [selectedKeys, setSelectedKeys] = useState<string[]>([])
  const [pageNum, setPageNum] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(10)
  const [total, setTotal] = useState<number>(0)
  // 指标树所有最底层节点
  const allChildKeys = useRef<string[]>([])
  const [expandedKeys, setExpandedKeys] = useState<Key[]>([])

  // 前往评分
  const goPoint = (record: any) => {
    const { code, score } = record

    dispatch({
      type: 'evaluationModel/function_getSchoolResourceInfo',
      payload: {
        batchCode,
        unitCode: code,
        questionCode: selectedKeys[0]
      },
      callback: (response) => {
        if (JSON.stringify(response.obj) == '{}') {
          message.warning('当前用户尚未上传资料')
          return
        } else {
          setStorage('schoolCode', code)
          if (score) {
            setStorage('score', JSON.stringify(score))
          }
          setStorage('breadcrumb', JSON.stringify(breadcrumb))
          history.replace({
            pathname: '/assignment/mark/special',
            query: {
              batchCode,
              type,
              questionCode: selectedKeys[0],
              page: pageNum.toString()
            }
          })
        }
      }
    })
  }

  //   将打分点转换为表格列
  const transferColumns = () => {
    return pointDetail.map((item) => ({
      title: item.name,
      key: item.code,
      render: (text: string, record: schoolInfoType, index: number) => {
        return (
          <Radio.Group
            value={
              record.score?.find((v) => Object.keys(v)[0] === item.code)?.[
                item.code
              ]
            }
          >
            {scoreRules.map((item) => (
              <Radio value={item.code} key={item.code}>
                {item.name}
              </Radio>
            ))}
          </Radio.Group>
        )
      }
    }))
  }
  const temp = transferColumns()

  const constantColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (_: string, record: object, index: number) => {
        return (
          <span>
            {((pageNum - 1) * pageSize + (index + 1))
              .toString()
              .padStart(2, '0')}
          </span>
        )
      },
      width: '100px',
      align: 'center'
    },
    {
      title: '学校名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center'
    }
  ]
  let operateColumns = [
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      render: (_: string, record: any, index: number) => {
        return (
          <span className={styles.ponint} onClick={() => goPoint(record)}>
            前往评分
          </span>
        )
      },
      align: 'center'
    }
  ]
  let columns: any[] = [...constantColumns, ...temp]
  if (columns.length > 2) {
    columns = [...columns, ...operateColumns]
  }

  const handlePageChange = (page: number, pageSize: number) => {
    setPageNum(page)
    setPageSize(pageSize)
  }
  const paginationProps = {
    current: pageNum, //当前页码
    pageSize, // 每页数据条数
    showTotal: () => <span>总共{total}项</span>,
    total, // 总条数
    onChange: (page: number, pageSize: number) =>
      handlePageChange(page, pageSize), //改变页码的函数
    hideOnSinglePage: false,
    showSizeChanger: false
  }

  const getPointInfo = (batchCode: string, type: string) => {
    dispatch({
      type: 'evaluationModel/function_getPointInfo',
      payload: {
        batchCode,
        type
      }
    })
  }

  // 获取打分规则
  const getScoringRules = () => {
    dispatch({
      type: 'evaluationModel/function_getScoringRules',
      payload: {}
    })
  }

  // 设置面包屑和请求学校数据
  const setBreadAndSchool = (key: string) => {
    setSelectedKeys([key])
    const temp = treeFindPath(pointInfo, (data) => data.code === key)
    setBreadcrumb(temp)
    getSchoolInfo({ batchCode, questionCode: key })
    setPageNum(1)
    setPageSize(10)
    formRef.current?.resetFields()
    dispatch({
      type: 'evaluationModel/function_getPointInfoByParentCode',
      payload: {
        batchCode: batchCode,
        parentCode: key,
        type
      }
    })
  }

  // 查看具体打分点
  const onSelect: TreeProps['onSelect'] = (selectedKeys) => {
    if (allChildKeys.current.includes(selectedKeys[0] as string)) {
      setBreadAndSchool(selectedKeys[0] as string)
    }
  }

  //    获取学校列表
  interface ParamsType {
    batchCode: string
    questionCode: string
    grade?: string
    unitName?: string
  }
  const getSchoolInfo = (params: ParamsType) => {
    const { batchCode, questionCode, grade, unitName } = params
    dispatch({
      type: 'evaluationModel/function_getSchoolInfo',
      payload: {
        batchCode,
        questionCode,
        grade,
        unitName
      }
    })
  }

  // 树字段标准化
  const treeFieldsFormat = (arr: PointInfoType[]): DataNode[] => {
    return arr?.map((item) => ({
      title: item.name,
      key: item.code,
      children: item.children ? treeFieldsFormat(item.children) : undefined
    }))
  }

  // 查询学段
  const getGradeInfo = () => {
    dispatch({
      type: 'evaluationModel/function_getGradeInfo',
      payload: {}
    })
  }

  // 搜索
  const onFinish = (values: FormValues) => {
    const { grade, unitName } = values
    getSchoolInfo({
      batchCode,
      questionCode: selectedKeys[0],
      grade: grade == '' ? undefined : grade,
      unitName
    })
    setPageNum(1)
    setPageSize(10)
  }

  const onExpand = (expandedKeys: Key[]) => {
    setExpandedKeys(expandedKeys)
  }

  // 表单重置
  const resetForm = () => {
    formRef.current?.resetFields()
    getSchoolInfo({ batchCode, questionCode: selectedKeys[0] })
    setPageNum(1)
    setPageSize(10)
  }

  useEffect(() => {
    getPointInfo(batchCode, type)
    getScoringRules()
    getGradeInfo()
  }, [])

  // 默认选中第一条
  useEffect(() => {
    if (pointInfo.length) {
      allChildKeys.current = getChildKeys(pointInfo)
      if (questionCode) {
        setSelectedKeys([questionCode])
        setBreadAndSchool(questionCode)
      } else {
        setSelectedKeys([allChildKeys.current?.[0]])
        setBreadAndSchool(allChildKeys.current?.[0])
      }

      // 展开tree全部节点
      const expankeys = getParentKeys(pointInfo)
      setExpandedKeys(expankeys)
      if (page) {
        setPageNum(Number(page))
      }
    }
  }, [pointInfo])

  useEffect(() => {
    setTotal(schoolInfo.length)
  }, [schoolInfo])

  return (
    <>
      <div className={styles['pannel-wrapper']}>
        <div className={styles['main-content']}>
          <div className={styles['left-pannel']}>
            <div className={styles['pannel-title']}>科室指标评价</div>
            <div className={styles['pannel-content']}>
              <Tree
                treeData={treeFieldsFormat(pointInfo)}
                onSelect={onSelect}
                selectedKeys={selectedKeys}
                onExpand={onExpand}
                expandedKeys={expandedKeys}
              />
            </div>
          </div>
          <div className={styles['right-pannel']}>
            <div className={styles['right-pannel-title']}>
              <span className={styles['title']}>科室评价打分板</span>
              <span className={styles['rules']}>
                评分规则: 符合(满分)、基本符合(半分)、不符合(零分)
              </span>
            </div>
            <div className={styles['pannel-content']}>
              <div className={styles['breadcrumb']}>
                <Form
                  layout={'inline'}
                  onFinish={onFinish}
                  ref={formRef}
                  initialValues={{ grade: '' }}
                >
                  <Form.Item label="学段" name="grade">
                    <Select
                      placeholder="请选择参与学段"
                      style={{ width: '200px' }}
                    >
                      <Option value="">全部</Option>
                      {gradeList.map((item) => (
                        <Option value={item.dictKey} key={item.dictKey}>
                          {item.dictValue}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                  <Form.Item label="学校名称" name="unitName">
                    <Input placeholder="请输入学校名称" />
                  </Form.Item>

                  <Form.Item>
                    <Button type="primary" htmlType="submit">
                      搜索
                    </Button>
                    <Button onClick={resetForm}>重置</Button>
                  </Form.Item>
                </Form>
                <Breadcrumb separator=">">
                  {breadcrumb?.map((item) => (
                    <Breadcrumb.Item key={item}>{item}</Breadcrumb.Item>
                  ))}
                </Breadcrumb>
              </div>
              <div className={styles['table-wrapper']}>
                <Table
                  dataSource={schoolInfo}
                  columns={columns}
                  rowKey="code"
                  pagination={paginationProps}
                  bordered
                  rowClassName={(record, index) => {
                    let className = 'light-row'
                    if (index % 2 === 1) className = 'dark-row'
                    return className
                  }}
                />
              </div>
            </div>
          </div>
        </div>

        <p className={styles['copy-right']}>
          Copyright@ 2016 成都乐培生科技有限公司 蜀ICP备15018125号
        </p>
      </div>
    </>
  )
}

const mapStateToProps = ({
  evaluationModel,
  loading
}: {
  evaluationModel: EvaluationStateType
  loading: Loading
}) => {
  return {
    evaluationModel,
    evaluationLoding: loading.models.evaluationModel
  }
}

export default connect(mapStateToProps)(OfficeEvaluationPage)
